package com.igeek.boot.controller;

import com.igeek.boot.common.Result;
import com.igeek.boot.entity.Orders;
import com.igeek.boot.service.OrderService;
import com.igeek.boot.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @package com.igeek.boot.controller
 * @Description
 * @Author LittlePunk [296526219@qq.ccom]
 * @Version 2022.1
 * @Date 2023/12/16 10:38
 */
@RestController
@RequestMapping("/order")
@Slf4j
@Api(tags = "订单接口")
public class OrderController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 自定义开始时间戳
     */
    private static final Long BEGIN_TIME_START = 1672531200L;

    public static final int COUNT_BITS = 32;


    @Autowired
    private OrderService orderService;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;


    @ApiOperation("创建订单")
    @PostMapping("create")
    public Result create(){
        Orders orders = orderService.createOrder();
        return new Result(true , "创建成功" , orders);
    }

    @ApiOperation("查询订单")
    @GetMapping("/{oid}")
    public Result create(@PathVariable("oid")Integer oid){
        Orders orders = orderService.findByOid(oid);
        return new Result(true , "查询成功" , orders);
    }

    //生成四位的短信验证码的接口
    @ApiOperation("生成四位短信验证码")
    @GetMapping("/sendSmsCode/{phone}")
    public Result sendSmsCode(String phone){
        if(phone.length()!= 11){
            return new Result(false, "手机号码不合法", null);
        }
        //生成四位的短信验证码
        String fourBitRandom = RandomUtil.getFourBitRandom();
        //将四位验证码和手机号存入redis中
        redisTemplate.opsForValue().set(phone,fourBitRandom);
        return new Result(true, "发送成功", null);
    }


    //秒杀案例

    /**
     * 生成唯一 ID 的主方法
     */
    public long soleId(String prefixKey){

        //1.生成时间戳，使用现在的时间与设置的开始时间戳相减
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond-BEGIN_TIME_START;

        //2.生成序列号
        //2.1 获取当前日期，精确到天
        String nowDay = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //2.2 进行 id 自增长，并且存放到 redis 中
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + prefixKey + ":" + nowDay);

        /**
         * 3.进行拼接并返回
         *
         * count<< COUNT_BITS 由于一共有 64 位，序列号需要占 32 位，所以将时间戳往前移 32 位
         *
         * 然后将时间戳与序列号进行 "或" 运算
         */
        return timestamp<< COUNT_BITS | count;

    }



}
